﻿using HCMS.CommonDtos;
using HCMS.Entities.Base;
using HCMS.Extensions;
using HCMS.IServices.Base;
using HCMS.Web.Manage.Filter;
using Microsoft.AspNetCore.Mvc;

namespace HCMS.Web.Manage.Controllers.Module.Base
{
    /// <summary>
    /// 系统 字典
    /// </summary>
    public class SystemDictionaryController : ModuleController
    {
        private readonly ISystemDictionaryAppService systemDictionaryAppService;

        public SystemDictionaryController(
            ISystemDictionaryAppService systemDictionaryAppService
         )
        {
            this.systemDictionaryAppService = systemDictionaryAppService;
        }

        #region 列表
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult List()
        {
            return View($"{BasePath}/Base/SystemDictionary/List.cshtml");
        }

        /// <summary>
        /// 列表 Ajax
        /// </summary>
        /// <returns></returns>
        [ActionName("List")]
        [HttpPost]
        public async Task<IActionResult> PostList()
        {
            var searchArgs = new SearchArgsDto()
            {
                Status = Request.Form["status"].ToInt(9999),

                SearchName = Request.Form["searchName"].ToString(""),
                SearchKey = Request.Form["searchKey"].ToString(""),

                ParentId = Request.Form["parentId"].ToInt(0)
            };

            var pager = new PagerArgsDto()
            {
                CurrentPageIndex = Request.Form["page"].ToInt(1),
                PageSize = Request.Form["limit"].ToInt(10)
            };

            var result = await systemDictionaryAppService.ManageList(searchArgs, pager);

            return Json(new { code = 0, data = result.Data, count = result.PagerInfo.RowCount, msg = "ok" });
        }
        #endregion

        #region 新增、编辑、保存
        /// <summary>
        /// 新增
        /// </summary>
        /// <returns></returns>
        public IActionResult Add()
        {
            var model = new SystemDictionary();
            return View($"{BasePath}/Base/SystemDictionary/Edit.cshtml", model);
        }

        /// <summary>
        /// 添加子级
        /// </summary>
        /// <param name="parentId">父级 Id</param>
        /// <returns></returns>
        public IActionResult AddChildren(int parentId = 0)
        {
            var model = new SystemDictionary()
            {
                ParentId = parentId
            };
            return View($"{BasePath}/Base/SystemDictionary/Edit.cshtml", model);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Edit(int id)
        {
            if (id <= 0)
            {
                return Content("参数无效");
            }

            var model = await systemDictionaryAppService.BaseFirstOrDefaultAsync(t => t.Id == id);
            if (model == null)
            {
                return Content($"没有找到【id：{id}】字典信息");
            }

            return View($"{BasePath}/Base/SystemDictionary/Edit.cshtml", model);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="systemDictionary"></param>
        /// <returns></returns>
        public async Task<IActionResult> Save(SystemDictionary systemDictionary)
        {
            SystemDictionary? result = null;

            if (systemDictionary == null)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "参数异常" });
            }
            if (string.IsNullOrWhiteSpace(systemDictionary.Title))
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "请填写标题" });
            }

            var parentId = Request.Form["ParentId"].ToInt(-1);
            if (parentId == -1)
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "请选择所属上级" });
            }

            // 自定义 字典值 必须唯一，不能重复
            if (!string.IsNullOrWhiteSpace(systemDictionary.DictionaryValue))
            {
                var hasRepeat = await systemDictionaryAppService.HasRepeatValue(systemDictionary.Id, systemDictionary.DictionaryValue);
                if (hasRepeat)
                {
                    return Json(new AjaxResultDto() { Code = 500, Message = "已存在相同的 字典值，请修改后再保存" });
                }
            }

            var parentPath = (await systemDictionaryAppService.BaseFirstOrDefaultAsync(t => t.Id == parentId))?.ParentPath;

            if (!string.IsNullOrWhiteSpace(parentPath))
            {
                var pathIdArray = parentPath.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var pathIdList = Array.ConvertAll(pathIdArray, int.Parse).ToList();
                pathIdList.Add(parentId);
                parentPath = string.Join(",", pathIdList);
            }
            else
            {
                parentPath = $"{parentId}";
            }

            var entity = await systemDictionaryAppService.BaseFirstOrDefaultAsync(t => t.Id == systemDictionary.Id);
            if (entity != null)
            {
                if (entity.Id == parentId)
                {
                    throw new Exception("不能选择自己作为上级，请重新选择");
                }

                await TryUpdateModelAsync(entity);
                entity.ParentId = parentId;
                entity.ParentPath = parentPath;
                entity.UpdateTime = DateTime.Now;
                entity.UpdateUser = CurrentAdmin.AdminName;
                result = await systemDictionaryAppService.BaseUpdateAsync(entity);
            }
            else
            {
                entity = new SystemDictionary();
                await TryUpdateModelAsync(entity);
                entity.ParentId = parentId;
                entity.ParentPath = parentPath;
                entity.CreateTime = DateTime.Now;
                entity.CreateUser = CurrentAdmin.AdminName;
                entity.UpdateTime = DateTime.Now;
                entity.UpdateUser = CurrentAdmin.AdminName;

                result = await systemDictionaryAppService.BaseInsertAsync(entity);
            }

            if (result != null)
            {
                return Json(new AjaxResultDto() { Message = "处理成功" });
            }
            else
            {
                return Json(new AjaxResultDto() { Code = 500, Message = "处理失败" });
            }
        }
        #endregion

        #region 获取字典树结构
        /// <summary>
        /// 获取字典树结构
        /// </summary>
        /// <returns></returns>
        [DefaultPermission]
        [HttpGet]
        public async Task<IActionResult> AllTree()
        {
            var result = await systemDictionaryAppService.GetAllTree();
            return Json(result);
        }
        #endregion
    }
}
